package com.zlwy.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import com.zlwy.application.GlobalApplication;
import com.zlwy.entity.AppInfo;
import com.zlwy.entity.Five;
import com.zlwy.entity.K_CandleEntity;

public class Util {

	public static int dip2px(float dipValue) {
		final float scale = GlobalApplication.context.getResources().getDisplayMetrics().density;
		return (int) (dipValue * scale + 0.5f);
	}

	public static int px2dip(float pxValue) {
		final float scale = GlobalApplication.context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}
	
	public static String getFileNameByUrl(String url) {
		if (url == null || "".equals(url.trim())) {
			return null;
		}
		return url.substring(url.lastIndexOf("/") + 1);
	}
	
	/**
	 * 判断是否有网络连接
	 * 
	 * @return
	 */
	public static boolean isNetworkConnected() {
		ConnectivityManager mConnectivityManager = (ConnectivityManager) GlobalApplication.context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
		if (mNetworkInfo != null) {
			return mNetworkInfo.isAvailable();
		}
		return false;
	}
	
	/**
	 * 判断SD卡是否存在
	 * @return
	 */
	public static boolean hasSdcard() {
		String status = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(status)) {
			return true;
		} else {
			return false;

		}
	}
	
	/**
	 * 获取资源字符串
	 * 
	 * @param id
	 * @return
	 */
	public static String getResourcesStr(int id) {
		return GlobalApplication.context.getString(id);
	}
	/**
	 * 获取资源字颜色
	 * 
	 * @param id
	 * @return
	 */
	public static int getResourcesColor(int id) {
		return GlobalApplication.context.getResources().getColor(id);
	}
	/**
	 * 小数点控制
	 * @param s
	 * @return
	 */
	public static String dealStrs(String s, int dLong){
		StringBuilder sb = new StringBuilder(s);
		int index = s.lastIndexOf(".");//寻找小数点的索引位置，若不是小数，则为-1
		if(index==-1){
			//说明不是小数点，往后面添加0,先要加个点
			sb.append(".");
			for(int i=0; i<dLong; i++){
				sb.append("0");
			}
			return sb.toString();
		}else{
			//说明是小数点，就要判断小数点长度，然后截取
			int len = s.substring(index + 1).length();//取得小数点后的数值，不包括小数点
			if(len>dLong){
				//小数点位置太长,需要截取
				sb.delete(index+1+dLong, s.length());
			}
			if(len<dLong){
				//小数点位数太短
				int l = dLong-len;
				for(int i=0; i<l; i++){
					sb.append("0");
				}
			}
		}
		return sb.toString();
	}
	
	/**
	 * 小数点控制
	 * @param s
	 * @return
	 */
	public static double dealDouble(double s, int dLong){
		int base = 1;
		for(int i=0; i<dLong; i++){
			base = base*10;
		}
		int sb = (int) (s*base);
		s = (float)sb/base;
		return s;
	}
	
	  /**
	   * desc:保存对象
	   
	   * @param context
	   * @param key 
	   * @param obj 要保存的对象，只能保存实现了serializable的对象
	   * modified:	
	   */
	  public static void saveObject(Context context,String key ,Object obj, String fileName){
	    try {
	      // 保存对象
	      SharedPreferences.Editor sharedata = context.getSharedPreferences(fileName, 0).edit();
	      //先将序列化结果写到byte缓存中，其实就分配一个内存空间
	      ByteArrayOutputStream bos=new ByteArrayOutputStream();
	      ObjectOutputStream os=new ObjectOutputStream(bos);
	      //将对象序列化写入byte缓存
	      os.writeObject(obj);
	      //将序列化的数据转为16进制保存
	      String bytesToHexString = bytesToHexString(bos.toByteArray());
	      //保存该16进制数组
	      sharedata.putString(key, bytesToHexString);
	      sharedata.commit();
	    } catch (IOException e) {
	      e.printStackTrace();
	    }
	  }
	  
	  /**
	   * desc:将数组转为16进制
	   * @param bArray
	   * @return
	   * modified:	
	   */
	  public static String bytesToHexString(byte[] bArray) {
	    if(bArray == null){
	      return null;
	    }
	    if(bArray.length == 0){
	      return "";
	    }
	    StringBuffer sb = new StringBuffer(bArray.length);
	    String sTemp;
	    for (int i = 0; i < bArray.length; i++) {
	      sTemp = Integer.toHexString(0xFF & bArray[i]);
	      if (sTemp.length() < 2)
	        sb.append(0);
	      sb.append(sTemp.toUpperCase());
	    }
	    return sb.toString();
	  }
	  
	  /**
	   * desc:将16进制的数据转为数组
	   * <p>创建人：聂旭阳 , 2014-5-25 上午11:08:33</p>
	   * @param data
	   * @return
	   * modified:	
	   */
	  public static byte[] StringToBytes(String data){
	    String hexString=data.toUpperCase().trim();
	    if (hexString.length()%2!=0) {
	      return null;
	    }
	    byte[] retData=new byte[hexString.length()/2];
	    for(int i=0;i<hexString.length();i++)
	    {
	      int int_ch;  // 两位16进制数转化后的10进制数
	      char hex_char1 = hexString.charAt(i); ////两位16进制数中的第一位(高位*16)
	      int int_ch1;
	      if(hex_char1 >= '0' && hex_char1 <='9')
	        int_ch1 = (hex_char1-48)*16;   //// 0 的Ascll - 48
	      else if(hex_char1 >= 'A' && hex_char1 <='F')
	        int_ch1 = (hex_char1-55)*16; //// A 的Ascll - 65
	      else
	        return null;
	      i++;
	      char hex_char2 = hexString.charAt(i); ///两位16进制数中的第二位(低位)
	      int int_ch2;
	      if(hex_char2 >= '0' && hex_char2 <='9')
	        int_ch2 = (hex_char2-48); //// 0 的Ascll - 48
	      else if(hex_char2 >= 'A' && hex_char2 <='F')
	        int_ch2 = hex_char2-55; //// A 的Ascll - 65
	      else
	        return null;
	      int_ch = int_ch1+int_ch2;
	      retData[i/2]=(byte) int_ch;//将转化后的数放入Byte里
	    }
	    return retData;
	  }
	  
	  /**
	   * desc:获取保存的Object对象
	   * @param context
	   * @param key
	   * @return
	   * modified:	
	   */
	  public static Object readObject(Context context,String key, String fileName){
	    try {
	      SharedPreferences sharedata = context.getSharedPreferences(fileName, 0);
	      if (sharedata.contains(key)) {
	         String string = sharedata.getString(key, "");
	         if(TextUtils.isEmpty(string)){
	           return null;
	         }else{
	           //将16进制的数据转为数组，准备反序列化
	           byte[] stringToBytes = StringToBytes(string);
	             ByteArrayInputStream bis=new ByteArrayInputStream(stringToBytes);
	             ObjectInputStream is=new ObjectInputStream(bis);
	             //返回反序列化得到的对象
	             Object readObject = is.readObject();
	             return readObject;
	         }
	      }
	    } catch (StreamCorruptedException e) {
	      // TODO Auto-generated catch block
	      e.printStackTrace();
	    } catch (IOException e) {
	      // TODO Auto-generated catch block
	      e.printStackTrace();
	    } catch (ClassNotFoundException e) {
	      // TODO Auto-generated catch block
	      e.printStackTrace();
	    }
	    //所有异常返回null
	    return null;		    
	  }
	  
	  /**
	   * 查询所有支持分享的应用信息
	   * 
	   * @param context
	   * @return
	   */
	  public static List<ResolveInfo> getShareApps(Context context) {
	    List<ResolveInfo> mApps = new ArrayList<ResolveInfo>();
	    Intent intent = new Intent(Intent.ACTION_SEND, null);
	    intent.addCategory(Intent.CATEGORY_DEFAULT);
	    intent.setType("text/plain");
	    PackageManager pManager = context.getPackageManager();
	    mApps = pManager.queryIntentActivities(intent, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
	    return mApps;
	  }

	  /**
	   * 得到应用列表
	   * 
	   * @return
	   */
	  public static List<AppInfo> getShareAppList(Context context) {
	    List<AppInfo> shareAppInfos = new ArrayList<AppInfo>();
	    PackageManager packageManager = context.getPackageManager();
	    List<ResolveInfo> resolveInfos = getShareApps(context);
	    if (null == resolveInfos) {
	      return null;
	    }
	    else {
	      for (ResolveInfo resolveInfo : resolveInfos) {
	        AppInfo appInfo = new AppInfo();
	        appInfo.setAppPkgName(resolveInfo.activityInfo.packageName);
	        appInfo.setAppLauncherClassName(resolveInfo.activityInfo.name);
	        appInfo.setAppName(resolveInfo.loadLabel(packageManager).toString());
	        appInfo.setAppIcon(resolveInfo.loadIcon(packageManager));
	        shareAppInfos.add(appInfo);
	      }
	    }
	    return shareAppInfos;
	  }
	  
	  /**
		 * UTC时间转化为正常时间
		 * @param utcTime
		 * @return
		 */
		public static String utc2Local(String utcTime) {
			long t = Long.parseLong(utcTime)*1000;
			Date date = new Date(t);
			SimpleDateFormat localFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
			String time = localFormater.format(date);
			return time;
		}
		
		/**
		 * 推迟一分钟
		 * @param utcTime
		 * @return
		 */
		public static String utcEndMinutel(String utcTime) {
			long t = Long.parseLong(utcTime)*1000+60000;
			Date date = new Date(t);
			SimpleDateFormat localFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
			String time = localFormater.format(date);
			return time;
		}
		
		/**
	     * 获取屏幕分辨率
	     * @param context
	     * @return
	     */
	    @SuppressWarnings("deprecation")
		public static int[] getScreenDispaly(Context context) {
			WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
			int width = windowManager.getDefaultDisplay().getWidth();// 手机屏幕的宽度
			int height = windowManager.getDefaultDisplay().getHeight();// 手机屏幕的高度
			int result[] = { width, height };
			return result;
		}
	    
		/**
		 * 退出
		 */
		public static void exit(){
			GlobalApplication.manager.exit();
//			GlobalApplication.bitmapCache.clearCache();
		}
		/**
		 * 关闭软键盘
		 */
		public static void closeKeyBoad(Context context, View view){
			InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);  
			boolean isOpen=imm.isActive();//isOpen若返回true，则表示输入法打开  
			if(isOpen){
				imm.hideSoftInputFromWindow(view.getWindowToken(), 0); 
			}
		}
		
		/**
		 * 获取两个时间差
		 * @param starts
		 * @param ends
		 * @return
		 */
		public static  String getDiffDays(String starts,String ends) {
			Long week = (long) (7*24*60*60*1000);
			if(starts!=null&&ends!=null){
				 long diff = Long.parseLong(ends) -  Long.parseLong(starts)*1000;   
				 long poor =  week-diff;
				 int days = (int) (poor / (1000 * 60 * 60 * 24));
				 int hours = (int) (poor % (1000 * 60 * 60 * 24))/(1000 * 60 * 60);
				 int minus = (int) (poor % (1000 * 60 * 60))/(1000*60);
				 int seconds = (int) (poor % (1000 * 60))/(1000);
				 StringBuilder sb = new StringBuilder();
				 sb.append(days).append("天").append(hours).append("时").append(minus).append("分").append(seconds).append("秒");
				 if((days==0&&hours==0&&minus==0&&seconds==0)||days<0||hours<0||minus<0||seconds<0){
					 return "冷却结束";
				 }
				return sb.toString();
			}else{
				return "冷却结束";
			}
			
		}
		
		/**
		 * 五档排序
		 */
		public static void sort(List<Five> fives){
			Comparator<Five> comp = new Comparator<Five>() {
				public int compare(Five f1, Five f2) {
					if(f1.getPrice().equals("")||f2.getPrice().equals("")){
						return 0;
					}
					float t1 = Float.parseFloat(f1.getPrice());
					float t2 = Float.parseFloat(f2.getPrice());
					if(t1<t2){
						return 1;
					}else if(t1==t2){
						return 0;
					}else{
						return -1;
					}
				}
			};
		    Collections.sort(fives,comp);
		}
		
		/**
		 * 蜡烛线排序
		 */
		public static void sortCandle(List<K_CandleEntity> candle){
			Comparator<K_CandleEntity> comp = new Comparator<K_CandleEntity>() {
				public int compare(K_CandleEntity f1, K_CandleEntity f2) {
					if(f1.getDate().equals("")||f2.getDate().equals("")){
						return 0;
					}
					float t1 = DateUtil.parseLong(f1.getDate());
					float t2 = DateUtil.parseLong(f2.getDate());
					if(t1==0||t2==0){
						return 0;
					}
					if(t1<t2){
						return 1;
					}else if(t1==t2){
						return 0;
					}else{
						return -1;
					}
				}
			};
		    Collections.sort(candle,comp);
		}
}
